/**
 * @sort 3
 * @name 订单信息
 */
const { api, resp } = require("apite")
const { getOrders } = require("../service/orders")
const { getLength } = require("../service/common")
const { DB } = require("../config")

/**
 * @name 订单列表
 * @param {number} pageSize 每页大小
 * @param {number} pageNum 第几页，默认从一开始
 * @param {number} [managerId] 客户ID
 * @param {number} [status] 订单状态
 * @param {string} [prodId] 关联产品
 */
api.get("/api/orders/list", async (ctx) => {
	const { managerId, prodId, status, pageNum, pageSize } = ctx.query

	try {
		const numb = pageNum > 0 ? Number(pageNum) : 1
		const size = pageSize > 0 ? Number(pageSize) : 5

		const data = await getOrders(false, {
			pageNum: numb,
			pageSize: size,
			managerId,
			prodId,
			status
		})

		const total = await getLength("orders", [
			{ key: "managerId", val: managerId },
			{ key: "status", val: status }
		])

		ctx.body = resp.list(data, total, { pageNum: numb, pageSize: size })
	} catch (error) {
		ctx.body = resp.fail("error")
	}
})

/**
 * @name 订单详情
 * @param {string} id 订单的唯一值
 */
api.get("/api/orders/detail", async (ctx) => {
	const { id } = ctx.query
	if (!id) {
		ctx.body = resp.fail("请传递ID属性")
		return
	}
	const numbId = Number(id)
	try {
		const data = await getOrders(true, { id: numbId })
		ctx.body = resp.ok(data[0])
	} catch (error) {
		ctx.body = resp.fail(error)
	}
})

/**
 * @name 订单状态变更
 * @param {number, string} id 订单的唯一值
 * @param {number} status 状态的id值：1-5
 */
api.post("/api/orders/status", async (ctx) => {
	const { id, status } = ctx.post
	if (!id) {
		ctx.body = resp.fail("请传递订单ID")
		return
	}

	const statusIds = [1, 2, 3, 4, 5]

	if (!statusIds.includes(status)) {
		ctx.body = resp.fail("状态id不正确")
		return
	}

	try {
		const [rows] = await DB.execute(
			"UPDATE `orders` SET `status`= ? WHERE id = ?",
			[status, id]
		)

		if (rows.affectedRows) {
			ctx.body = resp.ok("修改成功")
		} else {
			ctx.body = resp.ok("操作完成")
		}
	} catch (error) {
		ctx.body = resp.fail(error)
	}
})
